﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@page "/tgconfig/uploaddevice"
@namespace ThingsGateway.Web.Page
@using System.Linq.Expressions;
@using BlazorComponent;
@using Mapster;
@using Masa.Blazor.Presets;
@using System.IO;
@using TouchSocket.Core;
@inject IUploadDeviceService UploadDeviceService
@attribute [Authorize]
@inject MasaBlazor MasaBlazor
@attribute [RolePermission]
@inherits CultureComponentBase
@inject UserResoures UserResoures
@inject IDriverPluginService DriverPluginService
@layout MainLayout

<MRow>
    <MCol Md=2 Cols="12">
        <MCard Class="ma-2" Style="height: calc(100vh - 200px)">
            <MCardTitle>
                <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_searchName"
                            Outlined Label=@typeof(CollectDevice).GetDescription(nameof(CollectDevice.DeviceGroup)) />
            </MCardTitle>
            <MTreeview Style="height: calc(100vh - 320px);overflow-y:auto" Dense TItem="string" TKey="string" ActiveChanged=@(async a=>
                       {
                       if(search.DeviceGroup!=a.FirstOrDefault())
                       {
                       search.DeviceGroup=a.FirstOrDefault();
                       await datatableQuery();
                       }
                       } )
                       Items="_deviceGroups" ItemText="r=>r" ItemChildren="r=>null"
                       Search="@_searchName"
                       Activatable ItemKey=@(r=>r)>
            </MTreeview>
        </MCard>
    </MCol>
    <MCol Md=10 Cols="12">
        <div style="height: calc(100vh - 200px)">


            <AppDataTable @ref="_datatable" TItem="UploadDevice" SearchItem="UploadDevicePageInput"
                          AddItem="UploadDeviceAddInput" EditItem="UploadDeviceEditInput"
                          IsMenuOperTemplate=false SearchModel="search"
                          QueryCall="QueryCall" AddCall="AddCall" EditCall="EditCall" DeleteCall="DeleteCall"
                          FilterHeaders="FilterHeaders" Filters="Filters" ShowDetailButton
                                ShowQueryButton
                          ShowAddButton=@UserResoures.IsHasButtonWithRole("tguploaddeviceadd")
                          ShowDeleteButton=@UserResoures.IsHasButtonWithRole("tguploaddevicedelete")
                          ShowEditButton=@UserResoures.IsHasButtonWithRole("tguploaddeviceedit")>
                <SearchTemplate>
                    <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.Name" Clearable
                                        Outlined Label=@context.Description(x => x.Name) />
                    <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.PluginName" Clearable
                                        Outlined Label=@context.Description(x => x.PluginName) />
                </SearchTemplate>
                <OtherToolbarTemplate>
                    <MMenu OffsetY Context="menu">
                        <ActivatorContent>
                            <MButton @attributes="@menu.Attrs" Color="primary"
                                     Icon="@MasaBlazor.Breakpoint.SmAndDown"
                                     Class="my-1  mx-2 ">
                                @T("复制")
                                <AppChevronDown></AppChevronDown>
                            </MButton>
                        </ActivatorContent>
                        <ChildContent>
                            <MList>
                                <MListItem OnClick="()=>CopyDevice(context)"> @T("复制设备") </MListItem>
                            </MList>

                        </ChildContent>
                    </MMenu>
                    <MButton Class="my-1  mx-2" Loading=@isDownExport OnClick=DownDeviceExport Color="primary">
                        @T("导出")
                    </MButton>
                    <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("tguploaddeviceedit")) Class="my-1  mx-2" OnClick="()=>{ ImportExcel.Step=1;  ImportExcel.IsShowImport=true;}" Color="primary">
                        @T("导入")
                    </MButton>
                </OtherToolbarTemplate>
                <AddTemplate>
                    @GetRenderFragment(context)
                </AddTemplate>

                <EditTemplate>
                    @GetRenderFragment(context)

                </EditTemplate>


                <ItemColTemplate>
                    @switch (context.Header.Value)
                    {

                        case nameof(context.Item.Enable):
                            <EnableChip Value="context.Item.Enable">
                            </EnableChip>
                            break;
                        case nameof(context.Item.PluginId):
                            <span>
                                @(
                                    DriverPluginService.GetNameById(context.Item.PluginId)
                                    )
                            </span>
                            break;
                        default:
                            @context.Value
                            break;

                    }

                </ItemColTemplate>
            </AppDataTable>

        </div>
    </MCol>
</MRow>

<ImportExcel @ref=ImportExcel Import="SaveDeviceImport" Preview="DeviceImport" />

@code {
    async Task CopyDevice(IEnumerable<UploadDevice> data)
    {
        if (data.Count() == 0)
        {
            await PopupService.EnqueueSnackbarAsync(@T("需选择一项或多项"), AlertTypes.Warning);
            return;
        }
        await UploadDeviceService.CopyDevAsync(data);
        await datatableQuery();
        await PopupService.EnqueueSnackbarAsync("复制成功", AlertTypes.Success);

    }
}
@code {
    string _searchName;
    List<string> _deviceGroups = new();
    private UploadDevicePageInput search = new();


    ImportExcel ImportExcel;

    async Task SaveDeviceImport(Dictionary<string, ImportPreviewOutputBase> data)
    {
        await UploadDeviceService.ImportAsync(data);
        await datatableQuery();
        ImportExcel.IsShowImport = false;
    }
    Task<Dictionary<string, ImportPreviewOutputBase>> DeviceImport(IBrowserFile file)
    {
        return UploadDeviceService.PreviewAsync(file);
    }

}
    @code {
    [Inject] public JsInitVariables JsInitVariables { get; set; } = default!;
    [Inject]
    IJSRuntime JS { get; set; }
    bool isDownExport;
    async Task DownDeviceExport()
    {
        try
        {
            isDownExport = true;
            StateHasChanged();
            using var memoryStream = await UploadDeviceService.ExportFileAsync();
            memoryStream.Seek(0, SeekOrigin.Begin);
            using var streamRef = new DotNetStreamReference(stream: memoryStream);
            await JS.InvokeVoidAsync("downloadFileFromStream", $"上传设备导出{DateTime.UtcNow.Add(JsInitVariables.TimezoneOffset).ToString("MM-dd-HH-mm-ss")}.xlsx", streamRef);
        }
        finally
        {
            isDownExport = false;
        }

    }


    List<DriverPluginCategory> DriverPlugins;
    StringNumber tab;
    private async Task DriverValueChanged(UploadDeviceEditInput context, long pluginId)
    {
        if (pluginId > 0)
            context.PluginId = pluginId;
        else
            return;
        if (context.DevicePropertys == null || context.DevicePropertys?.Count == 0)
        {
            context.DevicePropertys = GetDriverProperties(context.PluginId, context.Id);
            await PopupService.EnqueueSnackbarAsync("插件附加属性已更新", AlertTypes.Success);
        }

    }
    List<DependencyProperty> GetDriverProperties(long driverId, long devId)
    {
        return ServiceExtension.GetBackgroundService<UploadDeviceWorker>().GetDevicePropertys(driverId, devId);
    }
    RenderFragment GetRenderFragment(UploadDeviceEditInput context)
    {
        RenderFragment renderFragment = null;
        renderFragment +=
    @<div>
        <MTabs @bind-Value="tab">
            <MTab Value="1" Style="height:50px;">   @T("基本信息")    </MTab>
            <MTab Value="2">    @T("扩展属性")     </MTab>
        </MTabs>

        <MTabsItems Value="tab">
            <MTabItem Value="1">
                <MCard Flat Class="ma-2">
                    <MSubheader Class="mt-4 font-weight-black"> @(context.Description(x => x.Name))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.Name />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.Description))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.Description />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.DeviceGroup))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.DeviceGroup />


                    <MSubheader Class="mt-4 font-weight-black">    @(typeof(UploadDeviceRunTime).GetDescription(nameof(UploadDeviceRunTime.PluginName)))  </MSubheader>
                    <MCascader Value="context.PluginId" Class="mt-3 mr-3" Clearable TValue=long TItem="DriverPluginCategory"
                               ValueChanged=@(a=>DriverValueChanged(context,a))
                               Items="DriverPlugins" ItemText="u => u.Name" ItemValue="u => u.Id" ItemChildren="u => u.Children"
                               MenuProps="@(props => { props.Auto = true; props.OffsetY = true; })"
                               ShowAllLevels="false" HideDetails="@("auto")" Height="30" Dense>
                    </MCascader>

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.Enable))  </MSubheader>
                    <EnableSwitch @bind-Value=@context.Enable />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.IsLogOut))  </MSubheader>
                    <EnableSwitch @bind-Value=@context.IsLogOut />

                </MCard>
            </MTabItem>
            <MTabItem Value="2">
                <MCard Flat Class="ma-2">
                    <MButton Class="my-3" OnClick=@(async() =>
                         {
                         if(context.PluginId>0)
                         {
                         context.DevicePropertys= GetDriverProperties(context.PluginId,context.Id);
                         }
                         else
                         {
                         await PopupService.EnqueueSnackbarAsync("需选择驱动",AlertTypes.Error);
                         }
                         }
                         ) Color="primary">
                        @T("刷新设备属性")
                    </MButton>
                    @if (context.DevicePropertys != null)
                    {
                        @foreach (var item in context.DevicePropertys)
                        {
                            <MSubheader Class="mt-4 font-weight-black"> @item.Description </MSubheader>
                            <MTooltip Disabled=item.Remark.IsNullOrEmpty() Bottom Context="tip">
                                    <ActivatorContent>
                                        @if (item.PropertyName.Contains("BigText"))
                                    {
                                        <MTextarea AutoGrow Dense @attributes="@tip.Attrs" Outlined HideDetails="@("auto")" @bind-Value=@item.Value />
                                    }
                                    else
                                    {
                                        <MTextField Type="@(item.PropertyName.Contains("Password") ? "password" : "text")" @attributes="@tip.Attrs" Dense Outlined HideDetails="@("auto")" @bind-Value=@item.Value />
                                    }
                                </ActivatorContent>
                                <ChildContent>
                                    <span>@item.Remark</span>
                                </ChildContent>
                            </MTooltip>
                        }

                    }
                </MCard>
            </MTabItem>
        </MTabsItems>
    </div>
    ;
        return renderFragment;
    }
}
